﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Windsor;
using Castle.Core.Resource;
using Castle.Windsor.Configuration.Interpreters;

namespace Nebular.ExpenseManagement.WebApplication
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        static IWindsorContainer _container;

        public static IWindsorContainer Container
        {
            get { return MvcApplication._container; }           
        }

        static IWindsorContainer CreateContainer()
        {             
//            AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
//                string err = ((Exception)e.ExceptionObject).ToString();
////                _log.Fatal(err);
//                Debug.Fail(err);
//            };
//            _log.Info("*** Starting up, running as " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
            var container = new WindsorContainer(
                            new XmlInterpreter(new ConfigResource(ConfigElement))
                            );
            //_log.Info("Ready for action");
            return container; 
        }
        const string ConfigElement = "castle";

        public override void Dispose()
        {
            try
            {
                if (_container != null)
                {
                    _container.Dispose();
                    _container = null;
                }
            }
            finally
            {
                base.Dispose();
            }
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");           
            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            _container = CreateContainer();
            GC.KeepAlive(_container["scheduler"]);
        }
    }
}